package net.wsnetwork.jawa.master;

import java.net.InetAddress;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import net.wsnetwork.jawa.common.Constants;

public class Master extends UnicastRemoteObject implements MasterInterface {
    private static final long serialVersionUID = -538439593478479794L;
    private static final Logger LOG = Logger.getLogger(Master.class.getCanonicalName());
    Map<InetAddress, BackendInfo> backends = new ConcurrentHashMap<InetAddress, BackendInfo>();

    protected Master() throws RemoteException {
        super();
    }

    @Override public void BackendPing(InetAddress backendAddress) throws RemoteException {
        if (!backends.containsKey(backendAddress)) {
            LOG.info("Added backend cache server: " + backendAddress);
        }

        BackendInfo info = new BackendInfo(0, Constants.NUM_BUCKETS, backendAddress);
        backends.put(backendAddress, info);
    }

    @Override public List<BackendInfo> GetBackends() {
        List<BackendInfo> result = new ArrayList<BackendInfo>();
        for (Entry<InetAddress, BackendInfo> entry : backends.entrySet()) {
            BackendInfo backendInfo = entry.getValue();
            Date lastPingTime = backendInfo.getLastPingTime();
            Date now = new Date();
            if (lastPingTime.getTime() + Constants.HEARTBEAT_INTERVAL * Constants.NUM_TIMEOUTS < now.getTime()) {
                LOG.info("Removed backend cache server: " + backendInfo.getAddress());
                backends.remove(backendInfo.getAddress());
            } else {
                result.add(backendInfo);
            }
        }
        return result;
    }
}
